package edu.stanford.bmir.protege.web.client.ui.ontology.transform;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.Widget;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.grid.CheckboxSelectionModel;

import edu.stanford.bmir.protege.web.client.ui.ontology.transform.service.TransformService;
import edu.stanford.bmir.protege.web.client.ui.ontology.transform.service.TransformServiceAsync;
import edu.stanford.bmir.protege.web.server.transform.service.StringWord;
import edu.stanford.bmir.protege.web.shared.transform.MappingBean;

public class StepTwo extends Composite {
	
	public static  Map<String,String> pros = new HashMap<String,String>();
	
	static {
		
		pros.put("BT", StringWord.SUBCLASSOF);
		pros.put("NT", StringWord.SUPCLASSOF);
		pros.put("RT", StringWord.OBJECTPROPERTY);
		pros.put("DDC", StringWord.DATAPROPERTY);
		pros.put("SN", StringWord.DATAPROPERTY);
		
		pros.put(StringWord.SIMPLENONPREFERREDTERM, StringWord.DATAPROPERTY);
    	pros.put( StringWord.CUSTOMNOTE , StringWord.DATAPROPERTY);
		
	}
	
	@UiField
	DataGrid<MappingBean> table;
	
	@UiField
	Button startImport;
	
	Map<String,String> cons ;
	
	List<String> sels ;
	
	List<MappingBean> mblst = new ArrayList<MappingBean>(); 
	

	private final TransformServiceAsync service = GWT.create(TransformService.class);
	
	private static StepTwoUiBinder uiBinder = GWT.create(StepTwoUiBinder.class);

	interface StepTwoUiBinder extends UiBinder<Widget, StepTwo> {
	}
	
	MainView view;
	
	SelectMapping mapping;
	
	String key;
	
	final CheckboxSelectionModel cbSelectionModel = new CheckboxSelectionModel(); 
	

	@SuppressWarnings("unchecked")
	public StepTwo( final MainView view ) {
		initWidget(uiBinder.createAndBindUi(this));
		
		this.view = view;
		
		cons = view.getConts();
		
		sels = view.getSels();
		
		mapping = new SelectMapping( this );
		
		//开始导入
		startImport.addClickHandler( new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				
				for ( String str : sels ) {
					MappingBean mb = new MappingBean();
					mb.setName( str );
					mb.setMapping( cons.get(str) );
					view.getMblst().add( mb );
				}
				
				view.openStepThree();
			}
		});
		
		
		service.getMappingList(view.getFileName(), new AsyncCallback(){

			@Override
			public void onFailure(Throwable caught) {
				
			}

			@Override
			public void onSuccess(Object result) {
				
				mblst = (List<MappingBean>) result;
				
				addGrid();
				
			}
			
		});
		
	}
		
	private void addGrid () {
		
		for ( MappingBean bean : mblst ) {

			String value = pros.get( bean.getName() );
			
			if ( !"".equals( value ) ) {
				bean.setMapping( value );
				cons.put( bean.getName() , value);
			}
			
		}
		
		
		table.setWidth( "600px" );
		table.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
		
		
		 final ProjectDisplayNameColumn projectNameColumn = new ProjectDisplayNameColumn();
	     table.addColumn(projectNameColumn, "");
		

		TextColumn<MappingBean> houseNumber = new TextColumn<MappingBean>() {
			@Override
			public String getValue(MappingBean object) {
				return object.getName();
			}
		};
		table.addColumn(houseNumber, "属性");
		
		TextColumn<MappingBean> country = new TextColumn<MappingBean>() {
			@Override
			public String getValue(MappingBean object) {
				return object.getMapping();
			}
		};
		table.addColumn(country, "本体映射");
		
		SelectMappingColumn smc = new SelectMappingColumn();
		
		table.addColumn(smc);

		table.setRowCount(mblst.size(), true);
		table.setRowData(0, mblst);
        
	}
	
	private class SelectMappingColumn extends Column<MappingBean, String> {

        private SelectMappingColumn() {
            super(new ClickableTextCell() {

            });
            setSortable(true);
        }

        @Override
        public String getValue(MappingBean object) {
            return object.getName();
        }

        @Override
        public void render(Cell.Context context, MappingBean object, SafeHtmlBuilder sb) {
            final String projectName = object.getName();
            SafeHtmlBuilder projectNameBuilder = new SafeHtmlBuilder();
            sb.appendHtmlConstant("<div>设置映射</div>");
        }

        @Override
        public VerticalAlignmentConstant getVerticalAlignment() {
            return HasVerticalAlignment.ALIGN_TOP;
        }

        @Override
        public void onBrowserEvent(Cell.Context context, Element elem, MappingBean object, NativeEvent event) {
            super.onBrowserEvent(context, elem, object, event);
            //mapping.showWindow();
            key = object.getName();
            openWindow (  );
            
        }
    }
	
	
	
	 private class ProjectDisplayNameColumn extends Column<MappingBean, String> {

	        private ProjectDisplayNameColumn() {
	            super(new ClickableTextCell() {

	            });
	            setSortable(true);
	        }

	        @Override
	        public String getValue(MappingBean object) {
	            return object.getName();
	        }

	        @Override
	        public void render(Cell.Context context, MappingBean object, SafeHtmlBuilder sb) {
	            sb.appendHtmlConstant("<div><input name='Fruit' type='checkbox' value='' /></div>");
	        }

	        @Override
	        public VerticalAlignmentConstant getVerticalAlignment() {
	            return HasVerticalAlignment.ALIGN_TOP;
	        }

	        @Override
	        public void onBrowserEvent(Cell.Context context, Element elem, MappingBean object, NativeEvent event) {
	            super.onBrowserEvent(context, elem, object, event);
	            
	            String key = object.getName();
	            
	            if ( sels.contains(key) ) {
	            	elem.setInnerHTML( "<div><input name='Fruit' type='checkbox'  /></div>" );
	            	sels.remove(key);
	            } else {
	            	elem.setInnerHTML( "<div><input name='Fruit' type='checkbox' checked /></div>" );
	            	sels.add( key );
	            }
	        }
	    }
	 
	 public void openWindow () {
		 
		 mapping = new SelectMapping( this );
		 mapping.showWindow();
		 
	 }
	
	public void setProperty ( String value ) {
		
		value = value.replace("<br>", "");
		
		for ( MappingBean bean : mblst ) {
			
			String name = bean.getName();
			if ( name!= null && name.equals( key ) ) {
				bean.setMapping( value );
			}
		}
		
		cons.put( key , value);
		
		table.redraw();
		
	}

	public int getSelectCount() {

        int length = sels.size();
        
        return length;
	}

}
